import 'package:flutter/material.dart';
import 'dart:math' as math;

import 'JoystickPainter.dart';

class CustomJoystick extends StatefulWidget {
  final double radiusInnerCircle;
  final double radiusOuterCircle;
  final double radiusTrack;
  final Function(double)? onAngleChanged;
  final VoidCallback? onReleased;

  CustomJoystick({
    Key? key,
    this.radiusInnerCircle = 50,
    this.radiusOuterCircle = 100,
    this.radiusTrack = 150,
    this.onAngleChanged,
    this.onReleased,
  }) : super(key: key);

  @override
  _CustomJoystickState createState() => _CustomJoystickState();
}

class _CustomJoystickState extends State<CustomJoystick> {
  late Offset blueDotPosition;
  late Offset center;
  bool isDragging = false;

  @override
  void initState() {
    super.initState();
    center = Offset(widget.radiusTrack, widget.radiusTrack);
    blueDotPosition = center;
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: (_) {
        setState(() {
          blueDotPosition = center;
          isDragging = false;
        });
      },
      onPanStart: (details) {
        RenderBox renderBox = context.findRenderObject() as RenderBox;
        Offset globalPosition = details.globalPosition;
        Offset localPosition = renderBox.globalToLocal(globalPosition);

        if ((localPosition - center).distance <= 20) {
          setState(() {
            isDragging = true;
          });
        }
      },
      onPanUpdate: (details) {
        if (!isDragging) return;

        RenderBox renderBox = context.findRenderObject() as RenderBox;
        Offset globalPosition = details.globalPosition;
        Offset localPosition = renderBox.globalToLocal(globalPosition);

        // Limit movement within the outer circle
        double distance = math.sqrt(math.pow(localPosition.dx - center.dx, 2) + math.pow(localPosition.dy - center.dy, 2));
        if (distance > widget.radiusTrack) {
          localPosition = Offset(
            center.dx + (localPosition.dx - center.dx) * widget.radiusTrack / distance,
            center.dy + (localPosition.dy - center.dy) * widget.radiusTrack / distance,
          );
        }

        setState(() {
          blueDotPosition = localPosition;
        });
      },
      onPanEnd: (details) {
        if (widget.onReleased != null) {
          widget.onReleased!();
        }

        setState(() {
          blueDotPosition = center;
          isDragging = false;
        });
      },
      child: CustomPaint(
        size: Size(widget.radiusTrack * 2, widget.radiusTrack * 2),
        painter: JoystickPainter(
          center: center,
          radiusInnerCircle: widget.radiusInnerCircle,
          radiusOuterCircle: widget.radiusOuterCircle,
          radiusTrack: widget.radiusTrack,
          blueDotPosition: blueDotPosition,
          onAngleChanged: widget.onAngleChanged,
        ),
      ),
    );
  }
}